<template>
  <el-form :model="friendLink" :rules="rules" v-loading="loading" ref="form" v-on:change="onFormChange">
    <el-form-item label="站点" prop="url">
      <el-input v-model="friendLink.url" v-on:change="onUrlChange" />
    </el-form-item>
    <el-form-item label="标题" prop="title">
      <el-input v-model="friendLink.title" />
    </el-form-item>
    <el-form-item label="图标" prop="favicon">
      <el-image :src="friendLink.favicon" />
      <el-input v-model="friendLink.favicon" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import {Options, Vue} from "vue-class-component";
import FriendLink from "@/domain/FriendLink";
import {REG_EXP_FRIEND_LINK} from "@/constants/RegExp";
import FriendLinkService from "@/service/FriendLinkService";

@Options({
  name: "FriendLinkForm",
  props: {
    modelValue: Object
  },
  emits: ["update:modelValue"],
  watch: {
    modelValue(value: FriendLink){
      if(value){
        this.friendLink = value;
      }else{
        this.friendLink = {url: "", title: "", favicon: ""}
      }
    }
  }
})
export default class FriendLinkForm extends Vue{
  modelValue: FriendLink
  friendLink: FriendLink
  loading: boolean

  rules = {
    url: {required: true, pattern: REG_EXP_FRIEND_LINK, message: "站点格式:http://xxx.xxx.xx 或 https://xxx.xxx.xx"},
    title: {required: true, message: "必填项"},
    favicon: {required: true, type: "url", message: "请填写合法的图标url地址"},
  }

  data(): any{
    return {
      friendLink: this.modelValue || {
        url: "",
        title: "",
        favicon: "",
      },
      loading: false
    }
  }

  /**
   * 自动填写
   */
  async onUrlChange(url: string): Promise<void>{
    this.loading = true;
    try {
      if (!REG_EXP_FRIEND_LINK.test(url)) return;
      this.friendLink.favicon = url + (url.endsWith("/") ? "/" : "") + "/favicon.ico";
      this.friendLink.title = await FriendLinkService.getStationTitle(url);
    }finally {
      this.loading = false;
    }
  }

  /**
   * 验证表单
   */
  async validate(): Promise<boolean>{
    return await (this.$refs.form as any).validate();
  }

  /**
   * 改变事件
   */
  onFormChange(): void{
    this.$emit("update:modelValue", this.friendLink);
  }
}
</script>

<style scoped>

</style>
